const mongoose = require('mongoose')
const bcrypt = require('bcrypt-nodejs')
const jwt = require('jsonwebtoken')
const User = mongoose.model('user')
const config = require('../config')
const { formatBody } = require('../tools')
const sendMail = require('../tools/mailer')

module.exports = {
  async signCode (ctx) {
    let { email } = ctx.request.body
    let Reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
    if (!email || !Reg.test(email)) {
      return ctx.body = formatBody(0, '请填写合法的邮箱')
    }
    let signCode = ''
    for (let i = 0; i < 6; i++) {
      signCode += Math.floor(Math.random() * 10)
    }
    ctx.session.signCode = signCode
    ctx.session.signCodeExp = Date.now() + 1000 * 60 * 5
    sendMail({
      to: [
        email
      ],
      subject: 'polyflow',
      text: `您的验证码为：${signCode}。请不要把验证码泄露给其他人！5分钟内有效。`
    }).then(info => {
      console.log(info)
    }).catch(err => {
      console.log(err)
    })
    return ctx.body = formatBody(1, 'ok')
  },
  async signUp (ctx) {
    let { nickname, email, password, signCode } = ctx.request.body
    if (!nickname || !email || !password || !signCode) {
      return ctx.body = formatBody(0, '昵称，邮箱，密码都不可为空')
    }
    if (signCode != ctx.session.signCode) {
      return ctx.body = formatBody(0, '验证码错误')
    }
    if (ctx.session.signCodeExp - Date.now() > 1000 * 60 * 5) {
      return ctx.body = formatBody(0, '验证码已失效，请重新获取')
    }
    let repemail = await User.find({ email: email })
    if (repemail.length) {
      return ctx.body = formatBody(0, '此邮箱已经被注册')
    }
    // password加盐
    password = bcrypt.hashSync(password, bcrypt.genSaltSync(10))
    // 新建该用户实例
    let user = new User ({ nickname, email, password })
    // let exp = Math.floor((new Date().getTime())/1000) + 60 * 60 * 24 * 30
    // let token = await jwt.sign({ user_id: user._id, exp }, config.server.SIGN_KEY)
    await user.save()
    return ctx.body = formatBody(1, '注册成功')
  },
  async login (ctx) {
    let { email, password } = ctx.request.body
    let user = await User.findOne({ email: email })
    if (!user) return ctx.body = formatBody(0, '不存在该用户')
    if (!password) return ctx.body = formatBody(0, '密码不可为空')
    if(bcrypt.compareSync( password, user.password)) {
      // 将该在线用户保存进socket集合
      user.lastOnline = new Date()
      user.save()
      // 生成token返回给客户端
      let exp = Math.floor((new Date().getTime())/1000) + 60 * 60 * 24 * 30
      let token = await jwt.sign({ user_id: user._id, exp }, config.server.SIGN_KEY )
      return ctx.body = formatBody(1, '登陆成功', {
        token,
        user: {
          _id: user._id,
          nickname: user.nickname,
          avatar: user.avatar,
          sex: user.sex,
          place: user.place,
          email: user.email
        }
      })
    }
    return ctx.body = formatBody(0, '密码错误')
  }
}